//
//  MCAppImagePreView.swift
//  Mercury
//
//  Created by 范强伟 on 2023/5/17.
//  Copyright © 2023 Mercury. All rights reserved.
//

import UIKit

class MCAppImagePreView: UIView {
    var selectItem:((String) -> Void)?
    
    var selectIndex: Int = 0 {
        didSet{ 
        }
    }
     
    
    var collectionList: [String] = [String]() {
        didSet{
            collectionView.reloadData()
            page.numberOfPages = collectionList.count
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .clear
        addSubview(collectionView)
        addSubview(page)
        page.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-safeAreaEdgeInsets.bottom - 20)
            make.height.equalTo(30)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: screenWidth, height: screenHeight-safeAreaEdgeInsets.top-safeAreaEdgeInsets.bottom)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        let view = UICollectionView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight), collectionViewLayout: layout)
        view.isPagingEnabled = true
        view.delegate = self
        view.dataSource = self
        view.bounces = false
         
        view.backgroundColor = UIColor.clear
        view.register(MCAppImagePreCell.self, forCellWithReuseIdentifier: "MCAppImagePreCell")
        view.showsHorizontalScrollIndicator = false
        return view
    }()
    
    override func layoutSubviews() {
        super.layoutSubviews()
        if selectIndex != 0{
            collectionView.scrollToItem(at: IndexPath(row: selectIndex, section: 0), at: .left, animated: false)
            page.currentPage = selectIndex
        }
    }
    
    lazy var page: UIPageControl = {
        let view = UIPageControl()
        view.pageIndicatorTintColor = .init("#FFFFFF",alpha: 0.32)
        view.currentPageIndicatorTintColor = .init("#FFFFFF",alpha: 0.84)
        return view
    }()
    
}

extension MCAppImagePreView: UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate{
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MCAppImagePreCell", for: indexPath) as! MCAppImagePreCell
        cell.imageUrl = collectionList[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return collectionList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        selectItem?(collectionList[indexPath.row])
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollViewEndScroll()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        scrollViewEndScroll()
    }
     
    
    func scrollViewEndScroll(){
        let index = collectionView.contentOffset.x / screenWidth
        page.currentPage = Int(index)
    }
}

class MCAppImagePreCell: UICollectionViewCell {
    
    var imageUrl: String! {
        didSet{
            guard let path = imageUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return  }
            var urls: URL? = URL(fileURLWithPath: path)
            if path.contains("http") {
                urls = URL(string: path)
            }
            imageView.imageView.kf.setImage(with: urls) { [weak self] result in
                switch result {
                case .success(let image):
                    self?.imageView.image = image.image
                case .failure(_):
                    self?.imageView.image = nil
                }
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .clear
        contentView.backgroundColor = .clear
        makeUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func makeUI() {
        contentView.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    lazy var imageView: ZoomImageView = {
        let imageView = ZoomImageView()
        imageView.backgroundColor = .black
        imageView.contentMode = .scaleAspectFit
        imageView.isUserInteractionEnabled = true
        return imageView
    }()
    
}

